package com.firexxx.study.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.firexxx.study.web.response.RestResponse;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2020/04/09 17:25
 */
@RestControllerAdvice
public class RestResponseBodyHandler implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        if (RestResponse.class.isAssignableFrom(returnType.getParameterType())) {
            return false;
        }
        if (StringHttpMessageConverter.class.isAssignableFrom(converterType)) {
            return false;
        }

        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof RestResponse) {
            return body;
        }

        return new ObjectMapper().writeValueAsString(RestResponse.success(body));
    }
}